import { Router } from "vue-router";
import { useUserStore } from "@/stores/user";
import { useAppStore } from "@/stores/app";
import { initNProgress } from "@/utils/pageTools/useNprogress";

const NProgress = initNProgress();

const whiteList = ["/login", "/register", "/forgot", "/404"];

export function setRouterGuards(router: Router) {
  router.beforeEach((to, from, next) => {
    if (to.path !== from.path) NProgress.start();

    const userStore = useUserStore();
    const appStore = useAppStore();
    const isLoggedIn = !!userStore.token;

    if (whiteList.includes(to.path)) {
      appStore.currentRoutePath = [to.fullPath];
      next();
    } else if (!isLoggedIn) {
      appStore.currentRoutePath = ["/login"];
      next("/login");
    } else {
      appStore.currentRoutePath = [to.fullPath];
      next();
    }
  });

  router.afterEach((to, _) => {
    document.title =
      typeof to.meta.title === "string"
        ? "统一平台 - " + to.meta.title
        : "统一平台";
    NProgress.done();
  });

  router.onError((error) => {
    console.error("路由错误:", error);
    NProgress.done();
  });
}
